<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <div class="_card">
        <el-form
            class="_form"
            ref="form"
            :rules="rules"
            :model="form"
            label-width="100px"
        >
          <el-form-item v-if="form.id" label="作业编号：">
            <el-input v-model="form.operation_no" disabled></el-input>
          </el-form-item>
          <el-form-item label="作业类别：" prop="operation_category" required>
            <operation-category-select v-model="form.operation_category">
            </operation-category-select>
          </el-form-item>
          <el-form-item label="上报单位：" prop="organization_id" required>
            <organization-select model_type="way"
                                 v-model="form.organization_id"
            ></organization-select>
          </el-form-item>
          <el-form-item label="巡查分类：" prop="exception_category" required>
            <exception-category-select type="way" :unit="form.organization_id"
                                       v-model="form.exception_category"
            ></exception-category-select>
          </el-form-item>
          <el-form-item label="打标地址：" prop="address" required>
            <el-cascader
                clearable
                v-model="form.area_id"
                class="ele-fluid"
                placeholder="请选择省市区"
                :options="regions"
                popper-class="ele-pop-wrap-higher"
                @change="changeArea"
            />
            <el-input
                v-model="form.address"
                readonly
                placeholder="请在地图上选择详细地址"
            ></el-input>
            <el-button size="mini" style="width: 100%; margin-top: 4px" @click="goHistory">查看历史标记记录</el-button>
          </el-form-item>
          <el-form-item label="单位可见：">
            <el-select
                clearable
                v-model="form.organization_show"
                placeholder="请选择单位是否可见"
                class="ele-fluid"
            >
              <el-option label="可见" :value="1"/>
              <el-option label="不可见" :value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item v-show="form.operation_category !== 2" label="是否处罚：">
            <el-select
                clearable
                v-model="form.penalty"
                placeholder="请选择是否处罚"
                class="ele-fluid"
            >
              <el-option label="是" :value="1"/>
              <el-option label="否" :value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item label="备注:">
            <el-input
                :rows="3"
                clearable
                type="textarea"
                :maxlength="200"
                v-model="form.description"
                placeholder="备注"
            />
          </el-form-item>
          <el-form-item label="异常图片:">
            <upload-image :limit="3" v-model="form.images"></upload-image>
          </el-form-item>
          <el-form-item>
            <el-button :loading="saveLoading" type="primary" @click="save">{{
                form.id ? '保 存' : '立即创建'
              }}
            </el-button>
            <el-button @click="$router.back()">取消</el-button>
          </el-form-item>
        </el-form>

        <!-- 点击获取位置 -->
        <MapContainer ref="map" :def-marker="form.lnglat" :icon="form.operation_category + ''" @callback="mapCb"/>

      </div>
    </el-card>
  </div>
</template>

<script>
import uploadImage from '@/components/uploadImage'
//import regions from 'ele-admin/packages/regions'
import organizationSelect from '@/components/organizationSelect'
import exceptionCategorySelect from './components/exceptionCategorySelect'
import operationCategorySelect from './components/operationCategorySelect'
import MapContainer from '@/components/Map/MapContainer'
import { regionData } from 'element-china-area-data'

export default {
  name: 'DiseaseEdit',
  components: {
    uploadImage,
    organizationSelect,
    exceptionCategorySelect,
    operationCategorySelect,
    MapContainer
  },
  data() {
    return {
      regions: regionData,
      loading: false,
      saveLoading: false,
      id: 0,
      form: {
        id: 0,
        operation_no: '',
        organization_id: null,
        operation_category: null,
        exception_category: null,
        area_id: [],
        address: '',
        organization_show: 1,
        penalty: 0,
        description: '',
        lng: '',
        lat: '',
        images: [],
        lnglat: []
      },
      rules: {
        operation_category: [
          {required: true, message: '请选择作业类别', trigger: 'change'}
        ],
        organization_id: [
          {required: true, message: '请选择上报单位', trigger: 'change'}
        ],
        exception_category: [
          {required: true, message: '请选择巡查分类', trigger: 'change'}
        ],
        address: [
          {required: true, message: '请选择打标地址', trigger: 'change'}
        ]
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.info(to.query.id)
    })
  },
  beforeRouteLeave(to, from, next) {
    this.form = {
      id: 0,
      operation_no: '',
      organization_id: null,
      operation_category: null,
      exception_category: null,
      area_id: [],
      address: '',
      organization_show: 1,
      penalty: 0,
      description: '',
      images: [],
      lng: '',
      lat: '',
      lnglat: []
    }
    this.$refs['form'].resetFields()
    next()
  },
  methods: {
    // 点击地图回调
    mapCb(data) {
      this.form.area_id = this.get(data.adcode)
      this.form.address = data.address
      this.form.lng = data.lnglat[0]
      this.form.lat = data.lnglat[1]
    },
    goHistory() {
      if (this.form.address) {
        let query = {
          addr: JSON.stringify({
            lnglat: this.form.lnglat,
            address: this.form.address,
          })
        }
        this.$router.push({
          path: '/road-traffic/disease/history',
          query: query
        })
      } else {
        this.$router.push('/road-traffic/disease/history')
      }
    },
    changeArea(val) {
      this.form.address = ''
      const getLabel = function (val, arr, index = 0, res = []) {
        for (let i in arr) {
          if (arr[i].value === val[index]) {
            res.push(arr[i].label)
            if (index === val.length - 1) {
              return res
            } else {
              return getLabel(val, arr[i].children, ++index, res)
            }
          }
        }
      }
      let city = getLabel(val, this.regions)
      this.$refs.map.setCenterByLocation(city.join())
    },
    // 根据区域id获取 省市区id
    get(value, arr = this.regions) {
      for (const obj of arr) {
        if (obj.value === value) {
          return [obj.value, ...this.get(value, obj.children || [])]
        }

        if (obj.children) {
          const res = this.get(value, obj.children)

          if (res.length) {
            return [obj.value, ...res]
          }
        }
      }

      return []
    },

    info(id) {
      if (!id) {
        return
      }
      this.loading = true
      this.$http
          .post('/disease/info', {id: id})
          .then((res) => {
            this.loading = false
            if (res.data.code === 0) {
              this.form = res.data.data
              this.form.lnglat = [this.form.lng, this.form.lat]
              this.$refs.map.setMarker(this.form.lnglat)
            } else {
              this.$message.error(res.data.msg)
            }
          })
          .catch((e) => {
            this.loading = false
            this.$message.error(e.message)
          })
    },
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.saveLoading = true
          this.$http
              .post('/disease/edit', this.form)
              .then((res) => {
                this.saveLoading = false
                if (res.data.code === 0) {
                  this.$message({type: 'success', message: res.data.msg})
                  this.$router.push('/road-traffic/disease/index')
                } else {
                  this.$message.error(res.data.msg)
                }
              })
              .catch((e) => {
                this.saveLoading = false
                this.$message.error(e.message)
              })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
._card {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

._form {
  width: 400px;
}
</style>